package tools

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"io"
)

func Jiami(plaintext string, key string) (encryptedText string, encryptedNonce string, err error) {
	plaintextByte := []uint8(plaintext)
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", "", err
	}

	aesGCM, err := cipher.NewGCM(block)
	if err != nil {
		return "", "", err
	}

	nonce := make([]byte, aesGCM.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return "", "", err
	}

	ciphertext := aesGCM.Seal(nil, nonce, plaintextByte, nil)
	encryptedText = base64.StdEncoding.EncodeToString(ciphertext)
	encryptedNonce = base64.StdEncoding.EncodeToString(nonce)

	return encryptedText, encryptedNonce, nil
}

func Jiemi(encryptedText, encryptedNonce, key string) (plaintext string, err error) {
	ciphertext, err := base64.StdEncoding.DecodeString(encryptedText)
	if err != nil {
		return "", err
	}

	nonce, err := base64.StdEncoding.DecodeString(encryptedNonce)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	aesGCM, err := cipher.NewGCM(block)
	if err != nil {
		return "", err
	}

	plaintextByte, err := aesGCM.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return "", err
	}

	return string(plaintextByte), nil

}
